package com.onlineMIS.action.headQ.user;


import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import net.sf.json.JSONObject;

import com.onlineMIS.ORM.DAO.JspLoadResult;
import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.MenuService;
import com.onlineMIS.ORM.DAO.headQ.user.SystemRoleMenuDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.user.UserInforService;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Menu;
import com.onlineMIS.ORM.entity.headQ.user.RoleFunctionality;
import com.onlineMIS.ORM.entity.headQ.user.SystemRoleMenu;
import com.onlineMIS.ORM.entity.headQ.user.UserFunctionalityDeleted;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.action.BaseAction;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.SessionInfo;
import com.onlineMIS.common.loggerLocal;
import com.onlineMIS.filter.SystemParm;
import com.opensymphony.xwork2.ActionContext;

import javassist.expr.NewArray;

@Controller
public class LoginAction extends BaseAction{

	private static final long serialVersionUID = 1L;
	@Autowired
	private UserInforService userInforService;

	@Autowired
	private SystemRoleMenuDaoImpl systemRoleMenuDaoImpl;
	@Autowired
	private MenuService menuService;

	private UserInfor user = new UserInfor();
	private boolean isAdmin;
	
	private int ipadRange;
    private Map<String,Object> jsonMap = new HashMap<String, Object>();
	private JSONObject jsonObject;


	public JSONObject getJsonObject() {
		return jsonObject;
	}


	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}



	public int getIpadRange() {
		return ipadRange;
	}


	public void setIpadRange(int ipadRange) {
		this.ipadRange = ipadRange;
	}
	public boolean getIsAdmin() {
		return isAdmin;
	}

	public void setIsAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}

	public UserInfor getUser() {
		return user;
	}

	public void setUser(UserInfor user) {
		this.user = user;
	}

	public String myTask(){
		return "myTasks";
	}
	
	/**
	 * 移动端，总部人员登录
	 * @return
	 */
	public String HqIpadLogin() {
	loggerLocal.info(this.getClass().getName() + ".HqIpadLogin");
		
		String userName = user.getUser_name();
		String password = user.getPassword();
		
		Response response = new Response();
		try { 
		     response = userInforService.validateUser(userName, password);
			if (response.getReturnCode() == Response.SUCCESS){
				UserInfor user = (UserInfor)response.getReturnValue();
				SessionInfo sessionInfo = new SessionInfo(user);
				ActionContext.getContext().getSession().put(Common_util.LOGIN_USER_MOBILE, sessionInfo);
				if(ipadRange == Common_util.ALL__RANGE) {
					ActionContext.getContext().getSession().put(Common_util.IPAD_DISTRIBUTION_SELECT_RANGE, Common_util.ALL__RANGE);
				}else if(ipadRange == Common_util.QX_RANGE) {
					ActionContext.getContext().getSession().put(Common_util.IPAD_DISTRIBUTION_SELECT_RANGE, Common_util.QX_RANGE);
				}else if (ipadRange == Common_util.XLC_RANGE) {
					ActionContext.getContext().getSession().put(Common_util.IPAD_DISTRIBUTION_SELECT_RANGE, Common_util.XLC_RANGE);
				}
				
				response.setSuccess("");
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.setFail("登录失败 : " + e.getMessage());
		} finally {
			jsonMap.put("response", response);
			jsonObject = JSONObject.fromObject(jsonMap);
		}

		return SUCCESS;
	}

	
	/**
	 * login for jsp head quarter user login
	 */
	public String login(){
		loggerLocal.info(this.getClass().getName() + ".login");
		
		String userName = user.getUser_name();
		String password = user.getPassword();
		
		Response response = new Response();
		try { 
		     response = userInforService.validateUser(userName, password);
			if (response.getReturnCode() == Response.SUCCESS){
				UserInfor user = (UserInfor)response.getReturnValue();
				userInforService.setFunctions(user);
				ActionContext.getContext().getSession().put(Common_util.LOGIN_USER, user);
				
				ActionContext.getContext().getSession().put(JspLoadResult.LOAD_RESULT, new JspLoadResult(JspLoadResult.LOAD_RESULT_INIT, null));
				/**
				 * 直接login到客户端
				 * 1: admin
				 * 2: non-admin
				 */
				if (isAdmin && user.containFunction(UserInfor.SWITCH_CHAIN_FUNCTION)){
					response.setReturnValue(1);
				} else 
					response.setReturnValue(2);	
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.setFail("登录失败 : " + e.getMessage());
		} finally {
			jsonMap.put("response", response);
			jsonObject = JSONObject.fromObject(jsonMap);
		}
		

		

		
		return SUCCESS;
	}
	

	
	/**
	 * login for json, head quarter user login
	 */
	public String reLogin(){
		loggerLocal.info(this.getClass().getName() + ".reLogin");
		String userName = user.getUser_name();
		String password = user.getPassword();
		
		Response response = userInforService.validateUser(userName, password);
		
		if (response.getReturnCode() != Response.SUCCESS){
			jsonMap.put("error", response.getMessage());
		} else {
			UserInfor user = (UserInfor)response.getReturnValue();
			userInforService.setFunctions(user);
			ActionContext.getContext().getSession().put(Common_util.LOGIN_USER, user);
			response.setReturnValue(null);
		}
		
		try{
			   jsonObject = JSONObject.fromObject(jsonMap);
			} catch (Exception e){
				loggerLocal.error(e);
			}
		
		return SUCCESS;
	}	
	
	/**
	 * this is the login from PDA
	 * @return
	 */
	public String PDALogin(){
		loggerLocal.info(this.getClass().getName() + ".PDALogin");
		int userId = user.getUser_id();
		String password = user.getPassword();

		Response response = userInforService.validateUser(userId, password);
		
		if (response.getReturnCode() == Response.SUCCESS){
			UserInfor user = (UserInfor)response.getReturnValue();
			//版本1：权限模块修改前 校验方式			
			//RoleFunctionality roleFunctionality = roleFunctionalityDaoImpl.getRoleFunctionality(user.getRoleType(),UserFunctionalityDeleted.PDA_FUNCTION);
			//版本2：判断权限标识
			Menu menu = menuService.selectMenuByPath(RoleFunctionality.SYSTEM_HQ_PDA);
			SystemRoleMenu systemRoleMenu = new SystemRoleMenu();
			if (menu != null) {
				systemRoleMenu = systemRoleMenuDaoImpl.getSystemRoleMenu(user.getRoleType(),menu.getId());
			}
						
			if (systemRoleMenu == null ){
				response.setQuickValue(Response.FAIL, "你的账户没有开通PDA开单功能");
			} else {
				userInforService.setFunctions(user);
				ActionContext.getContext().getSession().put(Common_util.LOGIN_USER, user);
			}
			
			response.setReturnValue(null);
		}
		
		
		
		jsonMap.put("response", response);
		
		try{
			   jsonObject = JSONObject.fromObject(jsonMap);
			} catch (Exception e){
				loggerLocal.error(e);
			}
		
		return SUCCESS;
	}
	
	/**
	 * 条码制作时客户登陆用
	 * @return
	 */
	public String login4Chain(){
		loggerLocal.info(this.getClass().getName() + ".login4Chain");
		String userName = user.getUser_name();
		String password = user.getPassword();
		
		Response response = userInforService.validateUser4Chain(userName, password);
		if (response.getReturnCode() == Response.SUCCESS)
			ActionContext.getContext().getSession().put(Common_util.LOGIN_CHAIN_USER, response.getReturnValue());
		
		jsonMap.put("response", response);
		
		try{
			   jsonObject = JSONObject.fromObject(jsonMap);
			} catch (Exception e){
				loggerLocal.error(e);
			}
		
		return SUCCESS;
	}
	
	/**
	 * 方便选货工作人员自动登录的
	 * @return
	 */
	public String autoLoginXuanhuo(){
		loggerLocal.info("UserJSPAction - autoLoginXuanhuo");
		Response response =new Response();
		try {
			response = userInforService.autoLoginXuanhuo(user);
		} catch (Exception e) {
			response.setFail("选货人员自动登录错误 : " + e.getLocalizedMessage());
		}
		
		if (response.isSuccess()) {
			ActionContext.getContext().getSession().put(Common_util.LOGIN_USER, response.getReturnValue());
		  return "xuanhuoLoginSuccess";
		} else {
		  addActionError(response.getMessage());
		  return "error";
		}
	}

}